/*************************************************************************
 * File Name:    First_Missing_Positive.cc
 * Author:       zero91
 * Mail:         jianzhang9102@gmail.com
 * Created Time: 2013/11/16 14:38:39
 * 
 * Description:  
 |------------------------------------------------------------------------
 | Problem: First Missing Positive
 |
 | Given an unsorted integer array, find the first missing positive integer.  
 |
 | For example,
 | Given [1,2,0] return 3,
 | and [3,4,-1,1] return 2.
 |
 | Your algorithm should run in O(n) time and uses constant space.
 |------------------------------------------------------------------------
 ************************************************************************/

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <deque>
#include <map>
#include <set>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>

using namespace std;

class Solution {
public:
    int firstMissingPositive(int A[], int n)
    {
        if (n == 0) return 1;
        
        int t, i, j, min_val;
        
        min_val = A[0] - 1;
        for (i = 0; i < n; ++i) {
            --A[i];
            min_val = min(min_val, A[i]);
        }
        min_val = min(min_val - 1, -2);
        
        for (i = 0; i < n; ++i) {
            j = A[i];
            while (j >= 0 && j < n) {
                t = A[j];
                A[j] = min_val;
                j = t;
            }
        }
        for (i = 0; i < n; ++i) {
            if (A[i] != min_val) break;
        }
        return i + 1;
    }
};

class Solution_Net {
    // This is a solution from the internet
public:
    int firstMissingPositive(int A[], int n) {
        int i = 0;
        while (i < n) {
            if (A[i] != i+1 && A[i] > 0 && A[i] <= n && A[A[i]-1] != A[i]) {
                swap(A[i], A[A[i]-1]);
            }
            else i++;
        }
        for (i = 0; i < n; i++)
            if (A[i] != i+1) break;
        return i+1;
    }
};

int
main(int argc, char *argv[])
{
    int A[] = {-5, 1000};
    Solution sol;

    cout << sol.firstMissingPositive(A, 2) << endl;


    return 0;
}
